package edu.dayu.service;

import edu.dayu.entity.pojo.MsgRecord;
import edu.dayu.mapper.MsgRecordMapper;
import edu.dayu.util.JacksonUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MsgRecordMapper msgRecordMapper;

    /**
     * 发送信息
     */
    public boolean sendMessage(String exchange,String routingKey,Object message){
        MsgRecord msgRecord = new MsgRecord();
        String msg = JacksonUtil.toJson(message);
        msgRecord.setMsg(msg);
        msgRecord.setExchange(exchange);
        msgRecord.setRouting(routingKey);
        int i = msgRecordMapper.insert(msgRecord);
        if (i==0) {
            throw new RuntimeException("插入消息失败"+msgRecord);
        }
        CorrelationData data = new CorrelationData();
        data.setId(msgRecord.getId().toString());
        MessageProperties properties = new MessageProperties();
        properties.setHeader("mid",msgRecord.getId());
        Message entity = MessageBuilder
                .withBody(msg.getBytes(StandardCharsets.UTF_8))
                .andProperties(properties)
                .build();
        rabbitTemplate.convertAndSend(exchange, routingKey, entity,data);
        return true;
    }
}
